<template>
	<div>
		<SearchHeader :search="search" @handlerSearch="handlerSearch">
		</SearchHeader>
		<TableCom
			ref="tableCom"
			url="/role"
			@handlerOperate="handlerOperate"
			:tableColumns="tableColumns"
			:tableOperate="tableOperate"
			:isTableIndex="true"
			:operateWidth="400"
		>
			<div slot="state" slot-scope="scope">
				<el-switch
				  @click.native="activeHandler(scope.row)"
					v-if="scope.row.state == 0"
					:value="scope.row.state"
					active-color="#13ce66"
					inactive-color="#ddd"
					:active-value=1
					:inactive-value=0
				>
				</el-switch>
				<el-switch
					@click.native="activeHandler(scope.row)"
					v-else
					:value="scope.row.state"
					active-color="#13ce66"
					inactive-color="#ddd"
					:active-value=1
					:inactive-value=0
				>
				</el-switch>
			</div>
		</TableCom>
		<el-dialog
			append-to-body
			:visible.sync="dialogTreeVisible"
			title="权限分配"
	>
		<el-tree
			:data="treeData"
			show-checkbox
			check-strictly
			highlight-current
			default-expand-all
			ref="tree"
			node-key="id"
			:default-expanded-keys="expandedKeys"
			:default-checked-keys="checkedKeys"
			:props="defaultProps">
				<div class="custom-tree-node" slot-scope="{ node, data }">
				<span
						:class="[
							'iconfont',
							data.type === 1 ? 'fw icon-caidan1' : '',
							data.type === 2 ? 'icon-anniu' : '',
							data.type === 3 ? 'icon-jiekou' : ''
						]"
						><i class="m">:</i>{{ data.name}}</span>
				</div>
		</el-tree>
		<div slot="footer" class="dialog-footer">
      <el-button @click="dialogTreeVisible = false">取 消</el-button>
      <el-button type="primary" @click="assignPermissions" :loading="loading">分配</el-button>
    </div>
	</el-dialog>
	</div>
</template>
<script>

export default {
	data () {
		return {
			loading : false,
			dialogTreeVisible : false,
			treeData : [],
			expandedKeys : [],
			checkedKeys : [],
			defaultProps : {
				children : 'children',
				label : 'label'
			},
			search : {
				// 搜索
				loading : false,
				form : [
					{
						type : 'text',
						label : '角色名:',
						placeholder : '请输入角色名',
						key : 'roleName'
					}
				],
				operates : [
					{
						type : 'search',
						color : 'primary',
						icon : 'el-icon-search',
						name : '查询'
					},
					{
						type : 'add',
						color : 'primary',
						icon : 'el-icon-circle-plus-outline',
						role : ['B_ROLE_SAVE'],
						name : '新增'
					}
				]
			},
			tableColumns : [
				// 表头
				{ name : '角色名', key : 'roleName' },
				{ name : '角色描述', key : 'description',tip : true },
				{ name : '状态', key : 'state' },
				{ name : '创建人', key : 'createName' },
				{ name : '创建时间', key : 'createTime', width : 170 },
				{ name : '最后更新时间', key : 'updateTime', width : 170}
			],
			tableOperate : [
				// 操作
				{
					name : '分配权限',
					type : 2,
					color : 'success',
					role : ['B_PERMISSION_ASSIGN'],
					icon : 'el-icon-user'
				},
				{
					name : '查看',
					type : 0,
					color : 'warning',
					role : [],
					icon : 'el-icon-view'
				},
				{
					name : '修改',
					type : 1,
					color : 'primary',
					role : ['B_ROLE_UPDATE'],
					icon : 'el-icon-edit'
				},
				{
					name : '删除',
					type : 3,
					color : 'danger',
					role : ['B_ROLE_DEL'],
					icon : 'el-icon-delete'
				}
			],
			dialogForm : [
				{
					type : 'text',
					label : '角色名',
					placeholder : '请输入角色名',
					key : 'roleName',
					maxlength : 10,
					rules : [
						{ required : true, message : '请输入角色名', trigger : 'blur' }
					]
				},
				{
					type : 'radio',
					label : '状态',
					placeholder : '请选择状态',
					key : 'state',
					options : [
						{
							value : 0,
							label : '禁用'
						},
						{
							value : 1,
							label : '启动'
						}
					],
					rules : [
						{ required : true, message : '请选择状态', trigger : 'blur' }
					]
				},
				{
					key : 'role',
					label : '权限分配'
				},
				{
					type : 'textarea',
					label : '角色描述',
					placeholder : '请输入角色描述',
					key : 'description',
					maxlength : 100
				}
			]
		};
	},
	created (){
		this.roleId  = '';
	},
	methods : {
		// 角色状态
		activeHandler (row){
			let tip = '';
			let state = row.state;
			if (row.state===0){
				tip = `是否启用【${row.roleName}】角色?`;
				state = 1;
			} else {
				tip = `是否禁用【${row.roleName}】角色?`;
				state = 0;
			}
			this.$confirm(tip,'提示',{
				confirmButtonText : '确定',
				cancelButtonText : '取消',
				beforeClose : async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						instance.confirmButtonText = '执行中...';
						try {
							await this.$api.roleUpdate({...row,state});
							this.$refs.tableCom.fetchData({
								pageNum : 1,
								pageSize : 100
							});
						} finally  {
							instance.confirmButtonLoading = false;
							done();
						}

					} else {
						done();
						this.$notify({
							title : '警告',
							message : '取消操作',
							type : 'warning'
						});
					}
				}
			});
		},
		// 搜索
		handlerSearch (types, data) {
			if (types.type === 'add'){
				this.$dialogForm.open({
					config : {
						title : '新增',
						leftButText : '取消',
						isRightBut : true
					},
					disabledAll : false,
					dialogForm : this.dialogForm,
					handlerFn : this.handlerRoleAdd
				});
			} else {
				this.search.loading = true;
				this.$refs.tableCom.fetchData(
					{
						pageNum : 1,
						pageSize : 100
					},
					data,
					() => {
						this.search.loading = false;
					}
				);
			}
		},
		// 新增角色
		async handlerRoleAdd (parameMap, callback) {
			try {
				await	this.$api.roleAdd(parameMap);
				callback(false);
				this.$refs.tableCom.fetchData({
					pageNum : 1,
					pageSize : 100
				});
			} catch (error) {
				callback(true);
			}
		},
		// 分配权限
		async assignPermissions (){
			const permissionIds = this.$refs.tree.getCheckedKeys();
			if (permissionIds.length ===0){
				this.$notify({
					title : '警告',
					message : '请勾选对应的权限',
					type : 'warning'
				});
				return;
			}
			try {
				this.loading = true;
				this.$api.assignPermission(this.roleId,permissionIds);
				this.dialogTreeVisible = false;
			} finally {
				this.loading = false;
			}
		},
		// 修改操作
		async handlerRoleUpdate (parameMap, callback) {
			try {
				parameMap.id = this.roleId;
				await	this.$api.roleUpdate(parameMap);
				callback(false);
				this.$refs.tableCom.fetchData({
					pageNum : 1,
					pageSize : 100
				});
			} catch (error) {
				callback(true);
			}
		},
		getCheckIds (menu,checkIds=[]){
			menu.forEach(item => {
				checkIds.push(item.id);
				if (item.children && item.children.length>0){
					this.getCheckIds(item.children,checkIds);
				}
			});
			return checkIds;
		},
		// 操作项
		async handlerOperate (operateItem, data) {
			this.roleId = data.id;
			switch (Number(operateItem.type)) {
			case 0:
				this.$dialogForm.open({
					config : {
						title : '查看',
						leftButText : '关闭',
						isRightBut : false
					},
					disabledAll : true,
					dialogForm : this.dialogForm,
					handlerFn : null,
					result : data
				});
				break;
			case 1:
				this.$dialogForm.open({
					config : {
						title : '修改',
						leftButText : '取消',
						isRightBut : true
					},
					disabledAll : false,
					dialogForm : this.dialogForm,
					handlerFn : this.handlerRoleUpdate,
					result : data
				});
				break;
			case 2:
				// eslint-disable-next-line no-case-declarations
				const result = await this.$api.getMenuAndBtnApi();
				const resultIds = await this.$api.getPermissionIdsByRoleId(data.id);
				this.treeData = result.data.menu;
				this.checkedKeys = resultIds.data;
				this.dialogTreeVisible = true;
				break;
			case 3:
				this.$confirm(`是否删除【${data.roleName}】角色?`,'提示',{
					confirmButtonText : '确定',
					cancelButtonText : '取消',
					beforeClose : async (action, instance, done) => {
						if (action === 'confirm') {
							instance.confirmButtonLoading = true;
							instance.confirmButtonText = '执行中...';
							try {
								await this.$api.roleDelete(data.id);
								this.$refs.tableCom.fetchData({
									pageNum : 1,
									pageSize : 100
								});
							} finally  {
								instance.confirmButtonLoading = false;
								done();
							}

						} else {
							done();
							this.$notify({
								title : '警告',
								message : '取消操作',
								type : 'warning'
							});
						}
					}
				});
				break;
			}
		}
	}
};
</script>
<style lang="scss" scoped>
.m{
	font-weight: bold;
	margin: 0 2px
}
.fw{
	font-weight: bold;
}
</style>
